package com.boyunv.observer.example01;
/*
 *@description
 * 享元工厂类:
 *   作用:作为存储享元对象的享元池,用户获取对象时,先从享元池中获取,有则返回  没有则创建新的并返回给用户
 *   并在享元池中保存
 *@author boyunv
 *@create 2023/8/8 7:14
 *@version 1.0
 */

import java.util.HashMap;
import java.util.Map;

public class FlyweightFactory {
 //定义一个map集合用于存储享元对象,实现享元池
 private Map<String,Flyweight> pool=new HashMap<>();
 //实现享元对象状态的传递
 public  FlyweightFactory(){
  //添加对应的内部状态
  pool.put("A",new ConcreteFlyweight("A"));
  pool.put("B",new ConcreteFlyweight("B"));
  pool.put("C",new ConcreteFlyweight("C"));

 }
 //根据内部状态进行查找
 public Flyweight  getFlyweight(String key){
  //对象是否存在
  if(pool.containsKey(key)){
   System.out.println("==享元池中存在,直接复用,key:"+key);
   return pool.get(key);
  }else {
   //如果对象不存在,就创建添加到享元池中
   System.out.println("====享元池中不存在,key"+key);
   Flyweight flyweight = new ConcreteFlyweight(key);
   pool.put(key,flyweight);
   return flyweight;
  }
 }

}
